﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.Text.RegularExpressions;
using System.Windows.Controls.Primitives;
using System.Threading;
using Cnblogs.Service;
using System.Collections.ObjectModel;
using Alexis.WindowsPhone;

namespace Cnblogs
{
    public partial class PostBodyPage : PhoneApplicationPage
    {
        public ObservableCollection<Entry> Items = new ObservableCollection<Entry>();
        public string currentPost = "";
        private int index = 0;
        private bool isLoaded = false;
        private Popup popUp;
        public PostBodyPage()
        {
            InitializeComponent();
            SetColor();
            popUp = new Popup();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!isLoaded)
            {
                isLoaded = true;
                var entry = (App.Current as App).CurrentEntry;
                Items = (App.Current as App).PostItems;
                index = Items.IndexOf(entry);
                FillUI();
                loadPost(entry.Id);
            }
            base.OnNavigatedTo(e);
        }

        private bool isRequesting = false;
        private void loadPost(string id)
        {
            if (isRequesting) return;
            isRequesting = true;

            GlobalIndicator.Instance.StartBusy();
            FeedService.Request(ServiceType.PostContent, new NewsData { Id = id }, (obj, isSuccess) =>
                {
                    isRequesting = false;
                    Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        currentPost = (obj as PostBody).Content;
                        string html = HtmlUtility.getHtml(HtmlUtility.RemoveLastImg(currentPost));
                        GlobalIndicator.Instance.StopBusy();
                        FillUI();
                        webBrowser.NavigateToString(html);
                    });
                    GlobalIndicator.Instance.StopBusy();
                });
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (popUp.IsOpen)
            {
                popUp.IsOpen = false;
                base.ApplicationBar.Mode = Microsoft.Phone.Shell.ApplicationBarMode.Default;
                e.Cancel = true;
                return;
            }
            base.OnBackKeyPress(e);
        }

        private void FillUI()
        {
            this.tbk_title.Text = Items[index].Title;
            this.tbk_source.Text = Items[index].AuthorInfo.Name;
            this.tbk_comments.Text = Items[index].Comments.ToString();
        }

        private void SetColor()
        {
            var color = GlobalFunc.IsDarkTheme ? new SolidColorBrush(Colors.White) : new SolidColorBrush(Colors.Black);
            var bgColor = GlobalFunc.IsDarkTheme ? new SolidColorBrush(Colors.Black) : new SolidColorBrush(Colors.White);
            this.tbk_title.Foreground = color;
            this.tbk_source.Foreground = color;
            this.tbk_comments.Foreground = color;
            this.LayoutRoot.Background = bgColor;
        }

        private void Appbar_Weibo_Click(object sender, EventArgs e)
        {
            App.Status = Constants.L_WeiboSharePost + Items[index].Title + " 猛击原文 " + Items[index].Link.Uri+" ";
            App.Status += HtmlUtility.filterHTML(Items[index].Summary);
            ThreadPool.QueueUserWorkItem((p) =>
            {
                string imgPath = HtmlUtility.getImageUrl(currentPost);
                if (!string.IsNullOrEmpty(imgPath))
                {
                    App.ShareImagePath = imgPath;
                    GlobalFunc.DownloadImage(imgPath);
                }
            });
            if (App.Token == null || App.Token.ExpiresTime.AddSeconds(30) <= DateTime.Now)
            {
                NavigationService.Navigate(new Uri(Constants.P_LoginWeiboPage, UriKind.Relative));
            }
            else
            {
                NavigationService.Navigate(new Uri(Constants.P_SendWeiboPage, UriKind.Relative));
            }
        }

        private void Menu_SMS_Click(object sender, EventArgs e)
        {
            GlobalFunc.OpenSMS(Constants.L_SharePost + Items[index].Title + string.Format(Constants.NewsUrlPrefix, Items[index].Id));
        }

        private void Menu_Email_Click(object sender, EventArgs e)
        {
            GlobalFunc.OpenEmail("", Constants.L_SharePost + Items[index].Title, HtmlUtility.filterHTML(Items[index].Summary) + string.Format(Constants.NewsUrlPrefix, Items[index].Id));
        }

        private void webBrowser_ScriptNotify(object sender, NotifyEventArgs e)
        {
            string input = e.Value.ToString();
            if (Regex.IsMatch(input, @"http://[^\[^>]*?(gif|jpg|png|jpeg|bmp|bmp)"))
            {
                base.ApplicationBar.Mode = Microsoft.Phone.Shell.ApplicationBarMode.Minimized;
                ImageSource source = new BitmapImage(new Uri(input, UriKind.Absolute));
                popUp.Height = 800;
                popUp.Width = 480;

                Grid grd = new Grid
                {
                    Height = 800,
                    Width = 480,
                    Background = App.Current.Resources["PhoneBackgroundBrush"] as SolidColorBrush,
                    Opacity = 0.9,
                };

                Image img = new Image { Source = source };

                grd.Children.Add(img);

                Button btnSave = new Button
                {
                    Content = "保存图片",
                    Height = 80,
                    Width = 200,
                    Margin = new Thickness(48),
                    VerticalAlignment = System.Windows.VerticalAlignment.Bottom
                };
                btnSave.Click += (e1, e2) =>
                {
                    GlobalFunc.SaveImage(img.Source as BitmapImage, DateTime.Now.ToFileTime().ToString());
                };
                grd.Children.Add(btnSave);

                popUp.Child = grd;
                popUp.IsOpen = true;
            }
            else
            {
                GlobalFunc.OpenBrowser(input);
            }
        }

        private void Appbar_Previous_Click(object sender, EventArgs e)
        {
            if (isRequesting) return;
            if (index == Items.Count - 1)
            {
                MessageBox.Show("已是最后一篇文章");
                return;
            }
            index++;
            loadPost(Items[index].Id);
        }

        private void Appbar_Next_Click(object sender, EventArgs e)
        {
            if (isRequesting) return;
            if (index == 0)
            {
                MessageBox.Show("已是第一篇文章");
                return;
            }
            index--;
            loadPost(Items[index].Id);
        }

        private void SavePost()
        {
            string content = webBrowser.SaveToString();
        }

        private void Menu_IE_Click(object sender, EventArgs e)
        {
            GlobalFunc.OpenBrowser(Items[index].Link.Uri);
        }

        private void Appbar_Save_Click(object sender, EventArgs e)
        {
            OfflineService.Current.SaveSinglePost(Items[index].Id, currentPost);
        }

        private void btn_comment_Click(object sender, RoutedEventArgs e)
        {
            if (Items[index].Comments == 0)
            {
                return;
            }
            NavigationService.Navigate(new Uri(Constants.P_CommentsPage + "?id=" + Items[index].Id + "&type=post&title=" + Items[index].Title, UriKind.Relative));
        }
    }
}